package elijah.base.widget;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lxj.xpopup.core.BasePopupView;

import java.lang.reflect.Method;

import elijah.base.R;
import elijah.base.databinding.ViewScanWidgetBinding;
import elijah.base.dialog.api.OnActionCallback;

public class ScanWidgetView extends FrameLayout {
    ViewScanWidgetBinding binding;
    private Callback callback;
    private String normalText;
    private String scanText;
    private int normalColor;
    private int scanColor;
    public static final String DEFAULT_NORMAL_TEXT = "点击扫描条码";
    public static final String DEFAULT_SCAN_TEXT = "条码扫码中...";


    public ScanWidgetView(@NonNull Context context) {
        this(context, null);
    }

    public ScanWidgetView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        binding = ViewScanWidgetBinding.inflate(LayoutInflater.from(getContext()), this, true);
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScanWidgetView);
            normalText = typedArray.getString(R.styleable.ScanWidgetView_normalText);
            normalText = TextUtils.isEmpty(normalText) ? DEFAULT_NORMAL_TEXT : normalText;
            binding.text.setText(normalText);
            scanText = typedArray.getString(R.styleable.ScanWidgetView_scanText);
            scanText = TextUtils.isEmpty(scanText) ? DEFAULT_SCAN_TEXT : scanText;
            normalColor = typedArray.getColor(R.styleable.ScanWidgetView_normalColor, getResources().getColor(R.color.alarmRed));
            scanColor = typedArray.getColor(R.styleable.ScanWidgetView_normalColor, getResources().getColor(elijah.base.R.color.alarmGreen));
            binding.text.setChipBackgroundColor(ColorStateList.valueOf(normalColor));

            typedArray.recycle();
        }
        init();
    }


    public ScanWidgetView setCallback(Callback callback) {
        this.callback = callback;
        return this;
    }

    private void init() {
        try {
            Class cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(binding.input, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        binding.input.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                InputMethodManager imm = (InputMethodManager) binding.input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(binding.input.getWindowToken(), 0);
                }
            } else {
                binding.text.setChecked(false);
            }

            if (callback != null) {
                callback.onFocusChange(hasFocus);
            }
        });

        setOnFocusChangeListener((view, b) -> {
            if (b) {
                binding.input.requestFocus();
                binding.text.setText(scanText);
                binding.text.setChipBackgroundColor(ColorStateList.valueOf(scanColor));
            }
        });


        binding.text.setOnCheckedChangeListener((compoundButton, checked) -> {
            if (checked) {
                binding.input.requestFocus();
                binding.text.setText(scanText);
                binding.text.setChipBackgroundColor(ColorStateList.valueOf(scanColor));

            } else {
                binding.text.setText(normalText);
                binding.input.clearFocus();
                binding.text.setChipBackgroundColor(ColorStateList.valueOf(normalColor));

            }
        });
        binding.text.setOnLongClickListener(view -> {
            new EditTextDialog(getContext())
                    .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_TEXT_FLAG_MULTI_LINE)
                    .show("输入条码", new OnActionCallback.Impl<String>() {
                        @Override
                        public void onSubmit(String value, BasePopupView dialog) {
                            callback.onData(value);
                            dialog.dismiss();
                        }
                    });
            return false;
        });

    }

    public ScanWidgetView setNormalText(String text) {
        this.normalText = text;
        if (!binding.text.isChecked()) {
            binding.text.setText(text);
        }
        return this;
    }


    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (callback == null) {
                return;
            }
            if (editable.toString().endsWith("\n")) {
                String trim = editable.toString().trim();
                callback.onData(trim);
                binding.input.setText("");
            }

        }
    };

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        binding.input.addTextChangedListener(watcher);

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        binding.input.removeTextChangedListener(watcher);

    }

    public void requestScan() {
        binding.text.setChecked(true);
    }

    public interface Callback {
        void onFocusChange(boolean focus);

        void onData(String data);
    }
}
